<?php

namespace app\index\observer;

use think\helper\Str;
use think\facade\Session;

use app\index\model\User as UserModel;
use app\index\model\Topic as TopicModel;

class Topic
{
    public function beforeInsert(TopicModel $topic)
    {
        $current_user = UserModel::currentUser();;
        if(empty($current_user)){
            $topic->user_id = 0;
        }else{
            $topic->user_id = $current_user->id;
        }
    }

    public function beforeWrite(TopicModel $topic)
    {
        $topic->excerpt = $this->makeExcerpt($topic->body);
    }

    /**
     * 生成话题摘要
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-21
     * @param    string             $value  话题正文
     * @param    integer            $length 摘要长度
     * @return   string                     生成摘要文本
     */
    protected function makeExcerpt($value, $length = 200)
    {
        $excerpt = trim(preg_replace('/\r\n|\r|\n+/', ' ', strip_tags($value)));
        return Str::substr($value, 0, $length);
    }
}
